<?php
/**
 * 供app调用支付宝提现接口
 * http://baseAddress/api/app/
 * @author Kenn
 * @todo 未做
 */
namespace App\Http\Controllers\Api\App;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Members\Members;
use App\Models\Alipay\AlipayRecord;
use Illuminate\Support\Facades\Input;

class AlipayController extends Controller
{

    /**
     *
     * 支付转账
     * @return json
     *
     */
    public function createAction()
    {
        $post = Input::all();

        $data['uid']    =isset($post['uid'])     ?$post['uid']    :false;
        $data['appId']  =isset($post['appId'])   ?$post['appId']  :false;
        $data['key']    =isset($post['key'])     ?$post['key']    :false;
        $data['email']  =isset($post['email'])   ?$post['email']  :false;
        $token          =isset($post['token'])   ?$post['token']  :false;
        $rsa            =isset($post['rsa'])     ?$post['rsa']    :false;//公用密钥


        if (!$data['uid'] || !$data['appId'] || !$data['key'] || !$data['email']) {
            return $this->respondJson(['data' => '请将参数填写完整！', 'code' => 402]);
        }

        //余额查询
        $member = Members::where(['id'=>$data['uid'],'appId'=>$data['appId'],'key'=>$data['key'],'email'=>$data['email']])->first();

        if (!$member) {
            return $this->respondJson(['data' => '该用户不存在', 'code' => 202]);
        }

        $token = md5(time()).md5(time());

        if ($member->money==0) {
            return $this->respondJson(['data' => '余额不足', 'code' => 203]);
        }

        $data['money']=$member->money;
        $data['created_at'] = date('Y-m-d H:i:s', time());

        //入库
        $AlipayRrecord = AlipayRecord::create($data);

        if (!$AlipayRrecord) {
            return $this->respondJson(['data' => '网络错误，请重新在试！', 'code' => 503]);
        }

        $member->money=0;
        $member->save();

        $res = ['uid'=>$AlipayRrecord->id];

        return $this->respondJson(['data' => $$res, 'code' => 0]);
    }

    /**
     *
     * 余额查询
     *
     * @todo 未做
     * @return json
     *
     */
    public function momey()
    {
        $post = Input::all();

        $key    = isset($post['key'])      ?$post['key']      :false;
        $appId  = isset($post['appId'])    ?$post['appId']    :false;
        $uid    = isset($post['uid'])      ?$post['uid']      :false;
        $token  = isset($post['token'])    ?$post['token']    :false;
        $rsa    = isset($post['rsa'])      ?$post['rsa']      :false;

        $member = Members::select('money')->where(['uid'=>$uid,'key'=>$key,'appId'=>$appId])->get();

        if (count($member)==0) {
            return $this->respondJson(['data' => '抱歉！没有找到该用户信息！', 'code' => 403]);
        }

        $token = md5(time()).md5(time());

        return $this->respondJson(['code'=>0,'data'=>$member->toArray()]);
    }
}
